package com.hxzy.service.impl;

import com.hxzy.bean.Message;
import com.hxzy.dao.MessageDao;
import com.hxzy.dao.impl.MessageDaoImpl;
import com.hxzy.service.DiscussService;
import com.hxzy.service.MessageService;
import com.hxzy.util.CommonUtil;
import com.hxzy.util.PageUtil;
import com.hxzy.vo.MessageVo;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nick
 */
public class MessageServiceImpl implements MessageService {
    private MessageDao messageDao = new MessageDaoImpl();

    @Override
    public int save(Message message) {
        return messageDao.save(message);
    }

    @Override
    public int update(Message message) {
        return messageDao.update(message);
    }

    @Override
    public int remove(Integer integer) {
        return messageDao.remove(integer);
    }

    @Override
    public List<Message> queryAll() {
        return messageDao.queryAll();
    }

    @Override
    public Message findById(Integer integer) {
        return messageDao.findById(integer);
    }

    @Override
    public PageUtil<MessageVo> queryAllMessage(PageUtil<MessageVo> pageUtil) {

        List<Message> messages = this.paging(pageUtil.getPageIndex(), pageUtil.getPageSize());

        //将 List<Message>集合转换为List<MessageVo>的集合
        List<MessageVo> collect = messages.stream().map(this::message2vo).collect(Collectors.toList());

        //将分页查询出的数据添加到分页工具类
        pageUtil.setData(collect);

        //查询总共有多少条数据
        int totals = this.totals();
        pageUtil.setTotals(totals);

        return pageUtil;
    }

    @Override
    public List<Message> paging(int pageIndex, int pageSize) {
        return this.messageDao.paging(pageIndex,pageSize);
    }

    @Override
    public int totals() {
        return this.messageDao.totals();
    }

    @Override
    public MessageVo findMessageById(int id) {
        Message message = this.findById(id);
        return message2vo(message);
    }

    private MessageVo message2vo(Message message) {
        MessageVo vo = new MessageVo();
        vo.setId(message.getId());
        vo.setTopic(message.getTopic());
        vo.setContent(message.getContent());
        //获取当前留言的发布时间
        LocalDateTime mesDate = message.getMesDate();
        //将时间转换为方言
        String dialect = CommonUtil.date2dialect(mesDate);
        vo.setDateDialect(dialect);

        vo.setNickName(message.getAuthor().getNickName());
        vo.setPic(message.getAuthor().getPic());

        DiscussService service = new DiscussServiceImpl();
        int messageReplyCount = service.getMessageReplyCount(message.getId());

        vo.setReplys(messageReplyCount);

        return vo;
    }
}
